<template>
  <a-tabs
      :activeKey="type"
      tab-position="left"
      :style="{ height: 'auto' }"
      @change="changeTabs"
  >
    <a-tab-pane key="base" tab="基础信息">
      <a-card title="用户信息" class="user-info-card">
        <template #extra>
          <a-button v-if="!isEditing" @click="toggleEdit(true)" class="edit-button">修改信息</a-button>
        </template>
        <form v-if="isEditing" @submit.prevent="saveInfo" class="edit-form">
          <a-form-item label="头像" class="form-item">
            <a-upload
                :show-upload-list="false"
                :before-upload="beforeUpload"
                @change="handleUploadChange"
            >
              <a-button>上传头像</a-button>
            </a-upload>
            <a-avatar :src="userInfo.avatarUrl" size="large" style="margin-left: 16px" />
          </a-form-item>
          <a-form-item label="用户名" class="form-item">
            <a-input v-model:value="userInfo.username" />
          </a-form-item>
          <a-form-item label="手机号" class="form-item">
            <a-input v-model:value="userInfo.phone" disabled />
          </a-form-item>
          <a-form-item label="邮箱号" class="form-item">
            <a-input v-model:value="userInfo.email" disabled />
          </a-form-item>
          <a-form-item class="form-item button-group">
            <a-button type="primary" html-type="submit" class="save-button">保存</a-button>
            <a-button style="margin-left: 8px" @click="toggleEdit(false)" class="cancel-button">取消</a-button>
          </a-form-item>
        </form>
        <div v-else class="info-display">
          <div class="avatar-and-name">
            <a-avatar :src="userInfo.avatarUrl" size="large" />
            <span class="username"><strong>用户名:</strong> {{ userInfo.username }}</span>
          </div>
          <p><strong>手机号:</strong> {{ userInfo.phone }}</p>
          <p><strong>邮箱号:</strong> {{ userInfo.email }}</p>
        </div>
      </a-card>
    </a-tab-pane>
    <a-tab-pane key="security" tab="安全设置">
      <ul class="security-list">
        <ContactBinding
            :contactType="'phone'"
            :isBound="isPhoneBound"
            :userInfo="userInfo"
            @bind="handleBind"
            @unbind="unbind"
            @sendCode="sendVerificationCode"
        />
        <ContactBinding
            :contactType="'email'"
            :isBound="isEmailBound"
            :userInfo="userInfo"
            @bind="handleBind"
            @unbind="unbind"
            @sendCode="sendVerificationCode"
        />
        <li class="security-item">
          <h3>密码修改</h3>
          <div style="display: flex; justify-content: space-between; align-items: center">
            <p style="margin: 0;" class="bound-phone-text">
              修改身份认证中心密码
            </p>
            <a-button>修改密码</a-button>
          </div>
        </li>
        <li class="security-item">
          <h3>二级认证</h3>
          <div style="display: flex; justify-content: space-between; align-items: center">
            <p style="margin: 0;" class="bound-phone-text">
              高风险操作时需要二级密码验证
            </p>
            <a-button
                v-if="!isSecondAuthEnabled"
                @click="toggleSecondAuth(true)"
            >
              开启二级验证
            </a-button>
            <a-button
                v-else
                @click="confirmDisableSecondAuth"
            >
              关闭二级验证
            </a-button>
          </div>
        </li>
      </ul>
    </a-tab-pane>
    <a-tab-pane key="bind" tab="账号绑定">
      <ul class="bind-list">
        <li class="bind-item">
          <h3>第三方账号绑定</h3>
          <div style="display: flex; justify-content: space-between; align-items: center">
            <p style="margin: 0;">微信账号</p>
            <a-button :disabled="isWechatBound" @click="bindWechat">
              {{ isWechatBound ? '已绑定' : '绑定微信' }}
            </a-button>
          </div>
        </li>
        <li class="bind-item">
          <h3>第三方账号绑定</h3>
          <div style="display: flex; justify-content: space-between; align-items: center">
            <p style="margin: 0;">QQ账号</p>
            <a-button :disabled="isQqBound" @click="bindQq">
              {{ isQqBound ? '已绑定' : '绑定QQ' }}
            </a-button>
          </div>
        </li>
      </ul>
    </a-tab-pane>
  </a-tabs>
  <!-- 二级认证确认关闭弹窗 -->
  <a-modal
      :open="isConfirmDisableSecondAuthModalVisible"
      title="确认关闭二级认证"
      @ok="toggleSecondAuth(false)"
      @cancel="cancelDisableSecondAuth"
  >
    <template #content>
      <p>关闭二级认证后，高风险操作将不再需要二级密码验证，是否继续？</p>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import ContactBinding from './ContactBinding.vue';
import {message} from "ant-design-vue";

const router = useRouter();
const route = useRoute();

// 初始化 type，确保不为 undefined
const type = ref<string>(route.query.type as string || 'base');

// 用户信息
const userInfo = ref({
  avatarUrl: '',
  username: 'John Doe',
  phone: '1234567890',
  email: 'johndoe@example.com',
  password: '123456' // 模拟密码
});

// 保存原始信息
const originalUserInfo = { ...userInfo.value };

// 是否处于编辑状态
const isEditing = ref(false);

// 手机号和邮箱号绑定状态
const isPhoneBound = ref(!!userInfo.value.phone);
const isEmailBound = ref(!!userInfo.value.email);

// 验证码
const verificationCode = ref({
  phone: '',
  email: ''
});

// 模拟的正确验证码
const correctVerificationCode = ref({
  phone: '',
  email: ''
});

// 用于绑定手机号和邮箱的临时变量
const newContactInfo = ref({
  phone: '',
  email: ''
});

// 二级认证是否开启
const isSecondAuthEnabled = ref(false);
// 确认关闭二级认证弹窗可见状态
const isConfirmDisableSecondAuthModalVisible = ref(false);

// 第三方账号绑定状态
const isWechatBound = ref(false);
const isQqBound = ref(false);

// 保存信息
const saveInfo = () => {
  console.log('保存的用户信息:', userInfo.value);
  // 更新原始信息
  Object.assign(originalUserInfo, userInfo.value);
  toggleEdit(false);
};

// 切换编辑状态
const toggleEdit = (edit: boolean) => {
  if (!edit) {
    // 恢复原始信息
    userInfo.value = { ...originalUserInfo };
  }
  isEditing.value = edit;
};

// 上传头像前的处理
const beforeUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('仅支持 JPG/PNG 格式的图片');
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB');
    return false;
  }
  return true;
};

// 处理头像上传变化
const handleUploadChange = (info: any) => {
  if (info.file.status === 'done') {
    // 这里假设上传成功后返回图片的 URL
    // 实际需根据接口返回调整
    userInfo.value.avatarUrl = info.file.response?.url || '';
  } else if (info.file.status === 'error') {
    message.error('头像上传失败');
  }
};

// 面板切换
const changeTabs = (key: string) => {
  type.value = key;
  try {
    router.push({ path: '/user/info', query: { type: key } });
  } catch (error) {
    message.error('路由跳转失败');
    console.error('路由跳转失败:', error);
  }
};

// 监听路由参数变化
watch(
    () => route.query.type,
    (newType) => {
      if (newType) {
        type.value = newType as string;
      }
    }
);

// 发送验证码
const sendVerificationCode = (type: 'phone' | 'email') => {
  if (newContactInfo.value[type]) {
    // 模拟生成验证码
    correctVerificationCode.value[type] = Math.floor(100000 + Math.random() * 900000).toString();
    console.log(`${type === 'phone' ? '手机号' : '邮箱号'}验证码:`, correctVerificationCode.value[type]);
    message.success('验证码已发送，请查收');
  } else {
    message.error(`请先输入${type === 'phone' ? '手机号' : '邮箱号'}`);
  }
};

// 处理绑定
const handleBind = (type: 'phone' | 'email') => {
  if (newContactInfo.value[type]) {
    if (verificationCode.value[type] === correctVerificationCode.value[type]) {
      userInfo.value[type] = newContactInfo.value[type];
      if (type === 'phone') {
        isPhoneBound.value = true;
      } else {
        isEmailBound.value = true;
      }
      newContactInfo.value[type] = '';
      verificationCode.value[type] = '';
      message.success(`${type === 'phone' ? '手机号' : '邮箱号'}绑定成功`);
    } else {
      message.error('验证码输入错误');
    }
  } else {
    message.error(`请输入有效的${type === 'phone' ? '手机号' : '邮箱号'}`);
  }
};


// 解绑
const unbind = (type: 'phone' | 'email') => {
  userInfo.value[type] = '';
  if (type === 'phone') {
    isPhoneBound.value = false;
  } else {
    isEmailBound.value = false;
  }
  message.success(`${type === 'phone' ? '手机号' : '邮箱号'}解绑成功`);
};

// 切换二级认证状态
const toggleSecondAuth = (enable: boolean) => {
  isSecondAuthEnabled.value = enable;
  isConfirmDisableSecondAuthModalVisible.value = false;
  message.success(`${enable ? '二级认证已开启' : '二级认证已关闭'}`);
};

// 确认关闭二级认证
const confirmDisableSecondAuth = () => {
  isConfirmDisableSecondAuthModalVisible.value = true;
};

// 取消关闭二级认证
const cancelDisableSecondAuth = () => {
  isConfirmDisableSecondAuthModalVisible.value = false;
};

// 绑定微信
const bindWechat = () => {
  // 这里可以添加实际的绑定逻辑
  isWechatBound.value = true;
  message.success('微信账号绑定成功');
};

// 绑定QQ
const bindQq = () => {
  // 这里可以添加实际的绑定逻辑
  isQqBound.value = true;
  message.success('QQ账号绑定成功');
};
</script>

<style scoped lang="less">
.user-info-card {
  width: 600px;
  margin: 0 auto;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.edit-button {
  background-color: #1890ff;
  color: white;
  border: none;
  &:hover {
    background-color: #40a9ff;
  }
}

.edit-form {
  padding: 20px;
}

.form-item {
  margin-bottom: 20px;
}

.button-group {
  margin-top: 30px;
}

.save-button {
  background-color: #52c41a;
  color: white;
  border: none;
  &:hover {
    background-color: #73d13d;
  }
}

.cancel-button {
  background-color: #f5222d;
  color: white;
  border: none;
  &:hover {
    background-color: #ff4d4f;
  }
}

.info-display {
  padding: 20px;
}

.avatar-and-name {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.username {
  margin-left: 16px;
  font-size: 18px;
}

.security-list {
  list-style-type: none;
  padding: 0;
}

.security-item {
  padding: 20px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.bound-phone-text {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.5);
}

.bind-list {
  list-style-type: none;
  padding: 0;
}

.bind-item {
  padding: 20px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

/* 为模态框内容添加一些内边距 */
.a-modal .ant-modal-content {
  padding: 20px;
}

/* 为模态框标题添加一些样式 */
.a-modal .ant-modal-title {
  font-size: 18px;
  font-weight: bold;
}

/* 为模态框的按钮添加一些间距 */
.a-modal .ant-modal-footer button + button {
  margin-left: 8px;
}
</style>